/* eslint-disable react-hooks/exhaustive-deps */
import { useCallback, useEffect, useState } from 'react'
import { InfiniteScroll, SpinLoading } from 'antd-mobile'
import type { Props } from './interface'
import styles from './index.module.less'
import { useLocation } from 'umi'
import noData from '@/resource/no_data.png'

let page = 0
export default function ScrollListView<T extends object, P>(props: Props<T, P>) {
    const { render, requestApi, params, noMoreText, renderHeader, noDataText } = props
    const [resData, setResData] = useState({})
    const [dataSource, setDataSource] = useState<T[]>([])
    const [total, setTotal] = useState<number>(0)
    const [loading, setLoading] = useState(true)
    const { auth_token } = useLocation().query

    const request = useCallback(
        async (isReload?: boolean) => {
            page = page + 1
            const requestParams = {
                per_page: 10,
                page,
                ...(params || ({} as P)),
            }
            const { data, headers, status }: any = await requestApi({
                ...requestParams,
                auth_token,
            }).finally(() => {
                setLoading(false)
            })
            setLoading(false)
            setResData(data)
            setDataSource(state => {
                // return isReload ? data : [...state, ...data]
                return isReload ? data : [...state, ...data]
            })
            page === 1 && setTotal(headers['x-pagination-total-count'])
        },
        [params],
    )
    const reload = () => {
        page = 0
        request(true)
    }

    useEffect(() => {
        request(true)
        return () => {
            page = 0
        }
    }, [request])

    const sliceArr = (data: T[]): { leftList: T[]; rightList: T[] } => {
        const leftList: T[] = []
        const rightList: T[] = []
        let isLeft = true
        data.forEach((item, index) => {
            if (isLeft && index !== data.length - 1) {
                leftList.push(item)
                isLeft = !isLeft
            } else {
                rightList.push(item)
                isLeft = !isLeft
            }
        })
        return { leftList, rightList }
    }

    const InfiniteScrollContent = ({ hasMore }: any) => {
        if (loading) {
            return <div />
        }
        if (!dataSource.length) {
            return (
                <div className={styles.no_data}>
                    <img src={noData} />
                    <div className={styles.no_data_text}>{noDataText || '暂无数据'}</div>
                </div>
            )
        }

        if (hasMore) {
            return <div className={styles.loadMore}>- 向下滑动加载更多 -</div>
        }

        return (
            <div className={styles.endText}>
                <div />
                <span>{noMoreText || '我还是有底线的'}</span>
                <div />
            </div>
        )
    }
    return (
        <>
            {renderHeader?.(resData)}
            {render(dataSource, reload, sliceArr(dataSource), loading)}
            <InfiniteScroll loadMore={() => request()} hasMore={dataSource.length < total}>
                <InfiniteScrollContent hasMore={dataSource.length < total} />
            </InfiniteScroll>
        </>
    )
}
